package com.ys.controller.api.storage;

import com.ys.config.MenuId;
import com.ys.entity.storage.TccStockStore;
import com.ys.entity.sys.YsCol;
import com.ys.service.storage.TccStockStoreService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 库存入库
 */
@Controller
@RequestMapping("/api/inter/tccStockStore")
public class ApiInterTccStockStoreController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccStockStoreController.class);

    @Autowired
    private CommonApiService<TccStockStore> commonApiService;

    @Autowired
    private TccStockStoreService tccStockStoreService;

    @Autowired
    private YspTaskService yspTaskService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccStockStore setSeachSql(TccStockStore cond){

        cond
                .addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeld ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人
                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("CASE WHEN P.UpdateTime IS NULL AND A.EffectStock = 1 THEN FORMAT(A.UpdateTime, 'yyyy-MM-dd HH:mm:ss') ELSE FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') END auditingTime")//审核时间
                .addLeftJoin("TCC_StockStoreItem B ON B.Pbid=A.Bid")
                .addLeftJoin("TB_CompanyInfo D ON D.Vid=B.CompanyVid")
                .addLeftJoin("TCC_Location TL ON TL.Chw=B.Chw")
                .addLeftJoin("THR_OperateCompanyApply TOC ON TOC.VGsBm=B.Vgsbm")

                .addLeftJoin("TCC_WarehouseArea TW ON TW.Ckq=TL.Ckq")
                .addLeftJoin("TCC_Warehouse TWh ON TWh.Cck=TW.Cck")
                .addLeftJoin("TB_Country TC ON TC.code = TWh.countryCode")
                .addField("TWh.Cck cck,TWh.Vck vck,TWh.CountryCode countryCode,TWh.City city,TC.name countryName")

                .addLeftJoin("TCC_StockControl tsc ON tsc.Id=B.StockControlId")
                .addField("B.StockControlId controlId,tsc.ProductName productName,tsc.ProductCode productCode,B.CodeMerge codeMerge,B.Price price," +
                        "tsc.ProductNum num,tsc.ProductNumAll productNumAll,tsc.RkBid sourceBid")

                .addField("FORMAT(B.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS drksj")//入库时间
                .addField("DATEDIFF(day, B.UpdateTime, getdate()) kcdays")//库存天数

                .addField("D.Vname companyVname,B.Num num," +
                        "TL.Vhw vhw,TW.Vkq vkq,TWh.Vck gdepot,TOC.VGsJc vgsjc,TOC.VGsBm vgsbm")
                //排序
                .setOrderby("A.Bid DESC");

        cond = commonApiService.dataAuth(MenuId.TCC_StockStore, cond);
        return  cond;
    }

    /**
     * 查询
     */
    @RequiresPermissions("tccStockStore:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TccStockStore cond, String conditions
    ){
        try {
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /*
     * 新增
     */
    @RequestMapping("/toAdd")
    @ResponseBody
    public R add(String bid, String remark, String subData,String vgsbm) {
        try {

            //修改
            return tccStockStoreService.add(bid, remark, subData,vgsbm);
        } catch (Exception e) {
            logger.error("库存入库新增出错：", e.getMessage(), e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    @RequiresPermissions("tccStockStore:add")
    public R edit(String bid, String remark, String subData) {
        try {
            return tccStockStoreService.edit(bid, remark, subData);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 删除
     * @throws Exception
     */
    @PostMapping("/delete")
    @ResponseBody
    public R delete(Long id){

        try {
            return tccStockStoreService.deleteTrue(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败，请联系客服");
        }
    }
    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccStockStore cond, String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TCC_StockStore)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            //处理数据
            ExportExcelUtils<TccStockStore> util = new ExportExcelUtils<>(new TccStockStore());
            String toFilePath = util.exportExcel(listData, listField, "库存入库单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }


    /**
     * 流转通过
     */
    @RequiresPermissions("tccStockStore:add")
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tccStockStoreService.flowPass(id, ShiroUtils.getUserId());
        }
        catch (RuntimeException e) {
            return R.error(e.getMessage());
        }
        catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转退回
     */
    @RequiresPermissions("tccStockStore:add")
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){
        try {
            return tccStockStoreService.flowRefuse(id, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 流转驳回
     */
    @RequiresPermissions("tccStockStore:add")
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){
        try {
            return tccStockStoreService.flowInit(id, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

}
        










